<template>
	<div class="productQuestion-add-update-component">
		<el-dialog
				v-if="modelValue.visible"
				v-model="modelValue.visible"
				:title="
        !modelValue.form.id
          ? `新增${modelValue.title}`
          : `修改${modelValue.title}`
      "
				width="550px"
		>
			<div style="padding-right: 50px; padding-top: 20px">
<el-form
		:model="modelValue.form"
		:rules="modelValue.rules"
		ref="addEditRef"
		:label-width="100"
>
	<el-form-item label="产品分类" prop="productId">
		<el-input
				placeholder="请输入产品分类"
				v-model="modelValue.form.productId"
				autocomplete="off"
		/>
	</el-form-item>
	<el-form-item label="常见问题" prop="question">
		<el-input
				placeholder="请输入常见问题"
				v-model="modelValue.form.question"
				autocomplete="off"
		/>
	</el-form-item>
	<el-form-item label="问题对应的答案" prop="answer">
		<el-input
				placeholder="请输入问题对应的答案"
				v-model="modelValue.form.answer"
				autocomplete="off"
		/>
	</el-form-item>

</el-form>
			</div>
			<template #footer v-if="!modelValue.form.disabled">
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="ensure"> 确定 </el-button>
        </span>
			</template>
		</el-dialog>
	</div>
</template>
<script  setup lang='ts'>
	import { ref, onMounted } from "vue";
	import { ElMessage, FormInstance } from "element-plus";
	import { addProductQuestion, updateProductQuestion } from "@/api/dms-product-question.api";

	const props = defineProps(["modelValue"]);
	const addEditRef = ref<FormInstance>();

	/***
	 * 确认弹框
	 */
	const ensure = () => {
		let form = props.modelValue.form;
		let formData = {
																				productId: form.productId,
																	question: form.question,
																	answer: form.answer,
									};

		if (!addEditRef.value) return;
		addEditRef.value.validate((valid, fields) => {
			if (valid) {
				if (form.id) {
					updateProductQuestion({
						...formData,
						id: form.id,
					})
							.then((res) => {
								cancel();
								ElMessage({
									message: props.modelValue.title + "修改成功",
									type: "success",
								});
								if (props.modelValue.refreshDataList) {
									props.modelValue.refreshDataList();
								}
							})
							.catch((err) => {
								ElMessage({
									message: err.msg || err,
									type: "error",
								});
							});
					return;
				}

				addProductQuestion(formData)
						.then((res) => {
							cancel();
							ElMessage({
								message: props.modelValue.title + "新增成功",
								type: "success",
							});
							if (props.modelValue.refreshDataList) {
								props.modelValue.refreshDataList();
							}
						})
						.catch((err) => {
							ElMessage({
								message: err.msg || err,
								type: "error",
							});
						});
			}
		});
	};

	/***
	 * 取消弹框
	 */
	const cancel = () => {
		props.modelValue.visible = false;
	};

</script>
<style lang='scss' scoped>
</style>
